<template>
  <div class="page-content">
    <Table
      :listData="listData"
      :listCount="listCount"
      :columnList="columnList"
      @selectionChange="handleSelectionChange"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      v-bind="contentTableConfig"
      :pageInfo="pageInfo"
      :isCreate="isCreate"
    >
      <!--1. header中插槽-->
      <template #headerHandler>
        <el-button v-if="isCreate" type="primary" size="small" @click="handleNewClick">
          添加
        </el-button>
      </template>
      <!-- 动态插入插槽-->
      <template v-for="item in columnList" :key="item.prop" #[item.slotName]="scope">
        <slot :name="item.slotName" :row="scope.row"> </slot>
      </template>
    </Table>
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, computed, onMounted, ref, nextTick } from 'vue'
import Table from '@/base-ui/table/index.vue'
import type { IPageInfo } from '@/types'
import { tableData } from '@/mockData/table'

const props = defineProps({
  // 表格配置项
  contentTableConfig: {
    type: Object,
    required: true
  },
  // 请求地址
  url: {
    type: String,
    required: true
  },
  // 查询参数
  queryParams: {
    type: Object,
    default: () => ({})
  },
  // 是否显示新增按钮
  isCreate: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['newBtnClick', 'handleSelectionChange'])
// 表格渲染列
const columnList = computed(() => props.contentTableConfig.columnList)

// 分页信息
const page = props.contentTableConfig.pageInfo

const pageData = page ? page : { currentPage: 1, pageSize: 10, pageOpt: [10, 20, 30, 40, 50] }

const pageInfo = ref<IPageInfo>(pageData)

onMounted(() => {
  queryTableData()
})

// 表格数据
const listData = ref<Array<any>>([])

// 数据总条数
const listCount = ref<number>(0)

const list = tableData

// 获取表格数据
const queryTableData = (params?: any) => {
  const searchData = params ? params : props.queryParams
  const data = {
    ...searchData,
    page: pageInfo.value.currentPage,
    size: pageInfo.value.pageSize
  }
  fetch(props.url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  })
    .then((res) => {
      console.log(res)
      listData.value = list
      listCount.value = 22
    })
    .catch((err) => {
      console.log(err)
    })
}

// 表格改变事件
const handleSelectionChange = (newSelection: any) => {
  emit('handleSelectionChange', newSelection)
}
// 分页条数改变
const handleSizeChange = (pageObj: IPageInfo) => {
  pageInfo.value = pageObj
  queryTableData()
}

// 页码改变
const handleCurrentChange = (pageObj: IPageInfo) => {
  pageInfo.value = pageObj
  queryTableData()
}
// 新增按钮点击事件
const handleNewClick = () => {
  emit('newBtnClick')
}

defineExpose({
  queryTableData
})
</script>

<style lang="less" scoped>
.page-content {
  height: 100%;
}
.handle-btns {
  display: flex;
  justify-content: space-around;
}
</style>
